package com.ruoyi.web.core.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.DatagramSocket;

@Component
//@EnableScheduling
public class UdpScheduler {

    @Autowired
    private UdpService udpService;

    //    private static final String TARGET_IP = "10.20.0.55";
    private static final int PORT = 7889;
    private static final int UDP_BUFFER_SIZE = 1024;
    private static final long POLLING_INTERVAL = 5000; // 轮询间隔，单位：毫秒
    private static final int TIMEOUT = 2000; // 接收数据的超时时间，单位：毫秒

    private static DatagramSocket socket = null;

//    @PostConstruct
    public void init() throws Exception {
        // 创建 DatagramSocket 并绑定源端口为 7889
        socket = new DatagramSocket(PORT);
        socket.setSoTimeout(TIMEOUT);
        // 接收udp 数据
        udpService.receiveData(socket);
    }

//    @Scheduled(fixedRate = 15000) // 每5秒执行一次
    public void scheduleUdpTask() {
        try {
            udpService.sendAndReceive(socket);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}